#! /bin/bash

if [ -n "$2" ] ;
then
  do_date=$2
else
  do_date=`date -d '-1 day' +%F`
fi

env_config="
use dw;
SET mapreduce.job.queuename=tianyan;
SET hive.input.format=org.apache.hadoop.hive.ql.io.HiveInputFormat;"

tmp_station_detail="
insert overwrite table dw.tmp_station_detail
select
       station_id,
       collect_set(fuel_no)[0],
       sum(quantity) as fuel_quantity,
       sum(c_pay_money),
       sum(c_discount_money),
       sum(mc_pay_money),
       sum(mc_discount_money),
       concat_ws(',', collect_set(rule_name)) as rule_name,
       concat_ws(',', collect_set(discount_type)) as discount_type,
       concat_ws(',', collect_set(discount_policy)) as discount_policy,
       sum(rebate_money),
       sum(real_rebate_money),
       date_format(dsod.dt, 'yyyy-MM-dd HH:mm:ss')
from dws_station_order_detail dsod
where dsod.dt in (
            select partition_dt
            from dim_partition
            where business_type = 2 and dt = '$do_date')
group by station_id, dsod.dt;
"

tmp_cart_detail="
insert overwrite table dw.tmp_cart_detail
select
       cart_id,
       collect_set(fuel_no)[0],
       sum(quantity) as fuel_quantity,
       sum(c_pay_money),
       sum(c_discount_money),
       sum(mc_pay_money),
       sum(mc_discount_money),
       concat_ws(',', collect_set(rule_name)) as rule_name,
       concat_ws(',', collect_set(discount_type)) as discount_type,
       concat_ws(',', collect_set(discount_policy)) as discount_policy,
       sum(rebate_money),
       sum(real_rebate_money),
       date_format(dsod.dt, 'yyyy-MM-dd HH:mm:ss')
from dws_station_order_detail dsod
where dsod.dt in (
            select partition_dt
            from dim_partition
            where business_type = 2 and dt = '$do_date')
group by cart_id, dsod.dt;
"


insert_into_table(){
  case $1 in
  "all")
    echo $1
    hive -e "$env_config$tmp_station_detail$tmp_cart_detail"
    ;;
  "tmp_station_detail")
    echo $1
    hive -e "$env_config$tmp_station_detail"
    ;;
  "tmp_cart_detail")
    hive -e "$env_config$tmp_cart_detail"
    ;;
  esac
}

insert_into_table $1

